<?php

use console\db\Migration;
use yii\db\Query;
use yii\db\Expression;
use yii\helpers\Console;
use yii\helpers\ArrayHelper;
use yii\base\Exception;

/**
 * 更新用户账户积分
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class m300200_100010_t_user_trend_exp_2016 extends Migration {

    const BATCH_SIZE = 500;

    /**
     * @inheritdoc
     */
    public $tableName = '{{%trend_log_2016}}';

    /**
     * @inheritdoc
     */
    public function safeUp() {
        $query = (new Query())->from($this->tableName)->select([
            'user_id as id', 'sum(num) as experience'
        ])->andWhere([
            'type' => 'exp'
        ])->groupBy('user_id');
        $this->handleProgress($query, [$this, 'evenDule']);
    }

    /**
     * 处理结果
     * @param Migration $migration
     * @param array $rows
     */
    public static function evenDule($migration, $rows) {
        if (empty($rows)) {
            return;
        }
        $connect = $migration->db->createCommand();
        foreach ($rows as $row) {
            $connect->upsert('{{%user_trend}}', $row, [
                'experience' => new Expression('experience + ' . $row['experience'])
            ])->execute();
        }
    }

}
